﻿using CommunityToolkit.Mvvm.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics;
using System.Reflection;
using System.Windows;
using TiaoTiaoCode.BasicDbCore;
using TiaoTiaoCode.Quartzer;
using TiaoTiaoCode.QuartzUI.ViewModels;

namespace TiaoTiaoCode.QuartzUI
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            var process = RunningInstance();
            if (process != null)
            {
                Shutdown();
                return;
            }

            RegistStartup();
            RegistType();

            base.OnStartup(e);
        }

        /// <summary>
        /// 注册视图
        /// </summary>
        static void RegistType()
        {
            Ioc.Default.ConfigureServices(
               new ServiceCollection()
               .AddTransient<MainViewModel>()
               //.AddScoped<IEnergyOpcConfService, EnergyOpcConfService>()
               //.AddScoped<IEnergyAreaRealService, EnergyAreaRealService>()
               //.AddScoped<IEnergyRealService, EnergyRealService>()
               //.AddScoped<IEnergyRuleService, EnergyRuleService>()
               //.AddScoped<IEnergyRuleAlarmService, EnergyRuleAlarmService>()
               .BuildServiceProvider()
               );
        }

        /// <summary>
        /// 注册启动类
        /// </summary>
        static void RegistStartup()
        {
            DbFramework.DbType = SqlSugar.DbType.Sqlite;
            DbFramework.Connection = "DataSource=Qrt.db";

            //DbFramework.DbType = SqlSugar.DbType.MySql;
            //DbFramework.Connection = "server=localhost;Database=esl;Uid=root;Pwd=123456;";

            TiaoTiaoQuartz.AddQuartzerStartup(DbFramework.Scope);
        }

        /// <summary>
        /// 获取当前程序运行进程
        /// </summary>
        /// <returns></returns>
        static Process? RunningInstance()
        {
            var current = Process.GetCurrentProcess();
            var processes = Process.GetProcessesByName(current.ProcessName);

            foreach (var process in processes)
            {
                if (process.Id != current.Id)
                {
                    // 确保例程从EXE文件运行 
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") != current.MainModule!.FileName)
                    {
                        return process;
                    }
                }
            }

            return null;
        }
    }
}
